package com.lsh.oms.worker.service.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dangdang.ddframe.job.api.JobExecutionMultipleShardingContext;
import com.dangdang.ddframe.job.plugin.job.type.simple.AbstractSimpleElasticJob;
import com.lsh.base.trace.id.filter.TraceIdSetter;
import com.lsh.oms.core.constant.Constants;
import com.lsh.oms.core.enums.OrderStatus;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.model.order.OrderSignHead;
import com.lsh.oms.core.proxy.service.DmallProxy;
import com.lsh.oms.core.redis.RedisTemplate;
import com.lsh.oms.core.service.order.OrderQueryService;
import com.lsh.oms.core.service.other.SignOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Project Name: lsh-oms
 *
 * @author peter
 * @date 18/2/27
 * 北京链商电子商务有限公司
 * Package:
 * desc:
 */
@Slf4j
@Component
public class BillNotifyDmallJop extends AbstractSimpleElasticJob {


    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    private SignOrderService signOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DmallProxy dmallProxy;

    @Override
    public void process(JobExecutionMultipleShardingContext jobExecutionMultipleShardingContext) {
        TraceIdSetter.set();
        try {

            Integer startTime = this.getStartTime();
            log.info("【推送多点订单已送达】统计范围 {}", startTime);
            List<OrderHead> orderHeads = orderQueryService.findListByStatusRangeAndTimeRange(OrderStatus.ORDER_SIGN.getIndex(), OrderStatus.ORDER_FINISH.getIndex(), startTime);

            if (CollectionUtils.isEmpty(orderHeads)) {
                log.info("【推送多点订单已送达】需要处理的数据集合是空-" + startTime);
                return;
            }

            orderHeads.stream().filter(orderHead -> pushFlag(orderHead))
                    .forEach(orderHead -> {
                        JSONObject req = new JSONObject();
                        Map<String, Object> ext = orderHead.extendedProperties();
                        req.put("maxOrderId", orderHead.getOrderCode() + "");
                        req.put("orderId", ext.get("remark"));
                        if (dmallProxy.pushDmall(req)) {
                            redisTemplate.set(Constants.PUSH_FINISH_KEY + orderHead.getOrderCode(), "push");
                        }else{
                            log.info("【推送多点订单已送达】已送达失败订单号 {}", orderHead.getOrderCode());
                        }
                    });

        } catch (Exception ex) {

            log.error("[推送多点订单状态] 异常", ex);
        }

    }

    /**
     * 过滤多点订单
     * @param orderHead
     * @return
     */
    private boolean pushFlag(OrderHead orderHead) {
        if (!StringUtils.isEmpty(redisTemplate.get(Constants.PUSH_FINISH_KEY + orderHead.getOrderCode()))) {
            return false;
        }

        JSONObject orderext = JSON.parseObject(orderHead.getAddressInfo());
        String duoDianOrder = orderext.getString("DuoDianOrder");
        if (StringUtils.isEmpty(duoDianOrder)) {
            log.info(orderHead.getOrderCode() + " duoDianOrder is " + duoDianOrder);
            return false;
        }

        if (duoDianOrder.equals("1")) {
            log.info(orderHead.getOrderCode() + " duoDianOrder is " + duoDianOrder);
            return false;
        }

        OrderSignHead orderSignHead = signOrderService.getSignHead(orderHead.getOrderCode());
        if (null == orderSignHead) {
            // 全单返仓
            log.info(orderHead.getOrderCode() + " 订单全单返仓或没有找到签收单-无法妥投");
            return false;
        }

        return true;
    }

    /**
     * 统计开始时间
     *
     * @return 时间戳
     */
    private Integer getStartTime() {

        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY) - 3);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
//        cal.add(Calendar.DATE, -1);

        return (int) TimeUnit.MILLISECONDS.toSeconds(cal.getTime().getTime());
    }


}
